import datetime
import geo.geomodel
import logging as log
import cgi
import os
import datetime
import random
import geo.geomath as geomath
import angels.user as usersDB
import angels.business as businessDB
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from django.utils import simplejson as json

class Sharing (db.Model):
    
	username = db.StringProperty(required=True)# Reporting user
	location = db.GeoPtProperty(required=True)
	description	= db.StringProperty(required=True)# when it will expire or was expired/released     
	create_time = db.DateTimeProperty(required=True)
	#business_key = db.StringProperty(required=True)
	category = db.StringProperty(required=True)
	subcategory = db.StringProperty(required=True)
	likes = db.IntegerProperty()
	dislikes = db.IntegerProperty()
	
	@staticmethod
	#def Create(geoPt, user, desc, bkey ,cat, sub):
	def Create(geoPt, user, desc ,cat, sub):
		sharing_report = Sharing(username = user, location=geoPt, description = desc, 
		create_time = datetime.datetime.now(), category = cat, subcategory = sub,
		likes=0,dislikes=0)
		#create_time = datetime.datetime.now(),business_key=bkey, category = cat, subcategory = sub,
		sharing_report.put()

class UpdateHandler(webapp.RequestHandler):
	
	def get(self):		
		key = self.request.get("key")		
		type = self.request.get("type")
		#value = self.request.get("value")
		share = Sharing.get(key)
		if (share):
			if (type=="likes"):
				share.likes+=1
			if (type=="dlikes"): 
				share.dislikes+=1
			share.put()
		else:
			self.response.out.write("no such share")
			return
			
class BroadcastHandler(webapp.RequestHandler):
    
    #Description: Add traffic report GET request handler
    #Params: user (string), location (x,y), desc
    #URL: /broadcast?user=Ilan Arbiv&loc=0.18352,2.845912&desc=hello there how are you?&cat=Places&sub=Tour&bkey=ag9kZXZ-YW5nZWxzLWRlbW9yDgsSCEJ1c2luZXNzGAEM

	def get(self):
        
		# broadcast location
		user = self.request.get("user")
		location = self.request.get("loc")
		desc = self.request.get("desc")
		cat = self.request.get("cat")
		sub = self.request.get("sub")
		bkey = self.request.get("bkey")
		
		#find the user
		foundUser=None	
		users = usersDB.User.all().filter('username',user)
		for foundUser in users:
			pass
		
		#find the business
		#if (bkey):
			#foundBusiness = businessDB.Business.get(bkey)		
		#else:
	#		self.response.out.write("no bkey was given")
	#		return
		
		#if (foundUser and foundBusiness):
		if (foundUser):
			if (not(user and location and desc and cat and sub)):
				self.response.out.write("not all params were given")
				return
		else:
			self.response.out.write("no such user or business")
			return
		
		lat, lon = location.split(',') # format is 'lat,lng'
		lat, lon = float(lat), float(lon)
		geoPt = db.GeoPt(lat, lon)  
	#	Sharing.Create(geoPt,user,desc,bkey,cat,sub)
		Sharing.Create(geoPt,user,desc,cat,sub)
		
class QueryHandler(webapp.RequestHandler):
    
    #Description: Query current traffic GET request handler
    #Params: None
    #URL: /traffic?cat=Places&sub=Tour
    
	def get(self):
		json_shares = []
		cat = self.request.get("cat")
		sub = self.request.get("sub")
		shares = Sharing.all().filter('category',cat).filter('subcategory',sub)
		for share in shares:    
			foundUser=None	
			users = usersDB.User.all().filter('username',share.username)
			for foundUser in users:
				pass
			json_share = {
			#	'bkey' : share.business_key,
				'desc': share.description,
				'user': share.username,
				'rat' : str(foundUser.rating),
				'loc' : str(share.location.lat)+","+str(share.location.lon),
				'ctime': str(share.create_time),
				'likes': str(share.likes),
				'dlikes': str(share.dislikes)
			}
			json_shares.append(json_share)
		json_res = {'robots': json_shares}
		self.response.out.write(json.dumps(json_res))